//
//  HMEmoticonModel.swift
//  表情键盘
//
//  Created by Apple on 16/7/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

/// 一个表情模型
class HMEmoticonModel: NSObject, NSCoding {
    /// 表情模型所在文件夹
    var id: String
    
    /// 表情名称,网络传输使用
    var chs: String?
    
    /// 表情图片名称
    var png: String? {
        didSet {
            // fullPngPath = bundlePath + / + id + png
            fullPngPath = HMEMoticonManager.sharedManager.bundlePath + "/" + id + "/" + png!
        }
    }
    
    /// 图片的完整路径
    var fullPngPath: String?
    
    /// emoji 16 进制字符串
    var code: String? {
        didSet {
            // 扫描
            let sacnner = NSScanner(string: code!)
            
            var result: UInt32 = 0
            // UnsafeMutablePointer<UInt32>: 要一个UInt32类型的指针
            sacnner.scanHexInt(&result)
            
            let scalar = UnicodeScalar(result)
            
            let c = Character(scalar)
            
            // 转成emoji
            emoji = String(c)
        }
    }
    
    /// emoji
    var emoji: String?
    
    init(id: String, dict: [String: String]) {
        self.id = id
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 模型输出
    override var description: String {
        get {
            return "\n\n\t\t表情模型: chs: \(chs), png: \(png), code: \(code)"
        }
    }
    
    // MARK: - 归档和解档
    required init?(coder aDecoder: NSCoder) {
        id = aDecoder.decodeObjectForKey("id") as? String ?? ""
        chs = aDecoder.decodeObjectForKey("chs") as? String
        png = aDecoder.decodeObjectForKey("png") as? String
        code = aDecoder.decodeObjectForKey("code") as? String
        emoji = aDecoder.decodeObjectForKey("emoji") as? String
        
        // fullPngPath = bundlePath + / + id + png
        // 每次运行 bundlePath 会变化,每次运行都重新拼接新的fullPngPath
        if png != nil {
            // 图片表情
            fullPngPath = HMEMoticonManager.sharedManager.bundlePath + "/" + id + "/" + png!
        }
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(id, forKey: "id")
        aCoder.encodeObject(chs, forKey: "chs")
        aCoder.encodeObject(png, forKey: "png")
        aCoder.encodeObject(code, forKey: "code")
        aCoder.encodeObject(emoji, forKey: "emoji")
    }
}
